# -*- coding:utf-8 -*-
from flask import request, jsonify, abort
from flask_cors import CORS
from com.zzh.dao_v2.couponDao import CouponDao
from com.zzh.dao_v2.memberDao import MemberDaoYM
from com.zzh.dao_v2.point_logDao import PointLogDao
from com.zzh.dao_v2.userDao import UserDao
from com.zzh.dao_v2.couponUsedDao import CouponUsedDao
from . import app
import time
localTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))

CORS(app, supports_credentials=True)


@app.route('/insert_coupon', methods=['POST'])
def insert_coupon():
    """
    添加信息
    :return:
    """
    if not request.json:
        abort(400)
    info = {
        'couponName': request.json.get('couponName', ''),
        'couponDescription': request.json.get('couponDescription', ''),
        'couponCode': request.json.get('couponCode', ''),
        'couponExpirationdate': request.json.get('couponExpirationdate', ''),
        'couponMemberNums': request.json.get('couponMemberNums', 0),
        'couponUsedTimes': request.json.get('couponUsedTimes', ''),
        'couponType': request.json.get('couponType', 0),
        'couponConditions': request.json.get('couponConditions', 0),
        'couponDiscount': request.json.get('couponDiscount', 0),
        'couponCreatedPerson': request.json.get('couponCreatedPerson', ''),
        'couponNeedPoints': request.json.get('couponNeedPoints', 0),
        'couponIsPoint': request.json.get('couponIsPoint', ''),
        'needPrice': request.json.get('needPrice')
    }

    info = CouponDao().insertCoupon(info)
    if info == -200:
        return jsonify({"message": {"code": 0, "status": "Database Exception: -200"}})
    elif info:
        return jsonify({"message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"message": {"code": 0, "status": "Server error!"}})

@app.route('/exchange_coupon',methods=['POST'])
def exchange_coupon():
    '''
    用户兑换优惠劵
    '''
    if not request.json:
        abort(400)
        userId=request.json.get('userId')
        couponIds=request.json.get('couponIds')

    userId = request.json.get('userId')
    MemPoint=MemberDaoYM().selectMemberByUserId(userId)[6]
    couponIds = request.json.get('couponIds')
    sum1=0
    for c in couponIds:
        sum1+=CouponDao().selectCoupon(c)[12]
    if MemPoint<sum1:
        return jsonify({"message": {"code": 0, "status": "points not enough"}})
    else:
        oldInfo = MemberDaoYM().selectMemberByUserId(userId)
        newInfo = {

            'id': request.json.get('id', oldInfo[0]),  #
            'userId': userId,  #
            'invited_code': request.json.get('invitedCode', oldInfo[2]),  #
            'member_code': request.json.get('memberCode', oldInfo[3]),  #
            'member_name': request.json.get('memberName', oldInfo[4]),

            'member_email': request.json.get('memberEmail', oldInfo[5]),  #
            'member_points': MemPoint-sum1,  #
            'member_balance': request.json.get('memberBalance', oldInfo[7]),  #
            'member_expired': request.json.get('memberExpired', oldInfo[8]),
            'industry_id': request.json.get('industryId', oldInfo[9]),

            'province_id': request.json.get('provinceId', oldInfo[10]),  #
            'city_id': request.json.get('cityId', oldInfo[11]),  #
            'district_id': request.json.get('districtId', oldInfo[12]),  #
            'member_favorite_count': request.json.get('memberFavoriteCount', oldInfo[13]),
            'member_address': request.json.get('memberAddress', oldInfo[14]),

            'member_busness': request.json.get('memberBusness', oldInfo[15]),  #
            'member_type': request.json.get('memberType', oldInfo[16]),  #
            'sp_knowledge': request.json.get('spKnowledge', oldInfo[17]),  #
            'sp_revenue': request.json.get('spRevenue', oldInfo[18]),
            'sp_employee': request.json.get('spEmployee', oldInfo[19]),

            'sp_industrycode': request.json.get('spIndustrycode', oldInfo[20]),  #
            'tm_industrycode': request.json.get('tmIndustrycode', oldInfo[21]),  #
            'tm_deptcode': request.json.get('tmEeptcode', oldInfo[22]),  #
            'tm_level': request.json.get('tmLevel', oldInfo[23]),
            'register_code': request.json.get('registerCode', oldInfo[23]),
            'is_vip': request.json.get('is_vip', 0)
        }

        MemberDaoYM().updateMemberByUserId(newInfo)
        for c in couponIds:
            pointLogInfo={
                'user_id':request.json.get('userId'),
                'username':UserDao().selectUser(request.json.get('userId'))[1],
                'point_item_name':CouponDao().selectCoupon(c)[1],
                'point_value':CouponDao().selectCoupon(c)[12],
                'remark':"cost",
                'is_income':2,
                'create_time':localTime
            }
            PointLogDao().add_point_log(pointLogInfo)
            couponInfo={
                'couponId':c,
                'userId':request.json.get('userId'),
                'timesUsed':1,
                'states':01
            }
            CouponUsedDao().insertCouponUsed(couponInfo)
        return  jsonify({ "message": {"code": 1, "status": "addReportCar OK"}})






@app.route('/find_coupon_by_id', methods=['POST'])
def find_coupon_by_id():
    """
    根据ID查询
    :return:
    """
    if not request.json:
        abort(400)
    couponId = request.json.get('couponId', '')
    info = CouponDao().findCouponById(couponId)

    if info:
        return jsonify({"info": info, "message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"message": {"code": 0, "status": "error"}})


@app.route('/find_coupon_by_condition', methods=['POST'])
def find_coupon_by_condition():
    """
    条件查询
    :return:
    """
    if not request.json:
        abort(400)

    try:
        page = request.json['page']
        pageIndex = page["pageIndex"]
        pageSize = page["pageSize"]
    except:
        return jsonify({"message": {"code": 0, "status": "请传入 pageIndex和pageSize"}})

    try:
        conditions = request.json['condition']
    except:
        return jsonify({"message": {"code": 0, "status": "未传入指定condition"}})
    try:
        multiSort = request.json['multiSort']
    except:
        return jsonify({"message": "未传入排序规则multiSort"})

    info, total = CouponDao().findCouponByCondition(pageIndex=pageIndex, pageSize=pageSize, conditions=conditions, multiSort=multiSort)

    if info:
        return jsonify({"total": total, "info": info, "message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"message": {"code": 0, "status": "error"}})

@app.route('/findCouponByCondition', methods=['POST'])
def findCouponByCondition():
    """
    条件查询
    :return:
    """
    if not request.json:
        abort(400)

    try:
        page = request.json['page']
        pageIndex = page["pageIndex"]
        pageSize = page["pageSize"]
    except:
        return jsonify({"message": {"code": 0, "status": "请传入 pageIndex和pageSize"}})

    try:
        conditions = request.json['condition']
    except:
        return jsonify({"message": {"code": 0, "status": "未传入指定condition"}})
    try:
        multiSort = request.json['multiSort']
    except:
        return jsonify({"message": "未传入排序规则multiSort"})

    info, total = CouponDao().findCouponViewByCondition(pageIndex=pageIndex, pageSize=pageSize, conditions=conditions, multiSort=multiSort)

    if info:
        return jsonify({"total": total, "info": info, "message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"message": {"code": 0, "status": "error"}})


@app.route('/delete_coupon_by_ids', methods=['POST'])
def delete_coupon_by_ids():
    """
    根据ID删除，ID以数组形式传递
    :return:
    """
    if not request.json:
        abort(400)
    idArray = request.json.get('idArray', [0])

    info = CouponDao().deleteCoupon(idArray)
    if info:
        return jsonify({"message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"message": {"code": 0, "status": "error"}})


@app.route('/update_coupon_by_id', methods=['POST'])
def update_coupon_by_id():
    """
    更新
    :return:
    """
    if not request.json:
        abort(400)
    try:
        couponId = request.json['couponId']
    except:
        return jsonify({"message": {"code": 0, "status": "请传入要修改信息的ID"}})
    oldInfo = CouponDao().selectCoupon(couponId)
    info = {
        'couponId': request.json['couponId'],
        'couponName': request.json.get('couponName', oldInfo[1]),
        'couponDescription': request.json.get('couponDescription', oldInfo[2]),
        'couponCode': request.json.get('couponCode', oldInfo[3]),
        'couponExpirationdate': request.json.get('couponExpirationdate', oldInfo[4]),
        'couponMemberNums': request.json.get('couponMemberNums', oldInfo[5]),
        'couponUsedTimes': request.json.get('couponUsedTimes', oldInfo[6]),
        'couponType': request.json.get('couponType', oldInfo[7]),
        'couponConditions': request.json.get('couponConditions', oldInfo[8]),
        'couponDiscount': request.json.get('couponDiscount', oldInfo[9]),
        'couponCreatedPerson': request.json.get('couponCreatedPerson', oldInfo[10]),
        'couponNeedPoints': request.json.get('couponNeedPoints', oldInfo[12]),
        'couponIsPoint': request.json.get('couponIsPoint', oldInfo[13]),
        'needPrice': request.json.get('needPrice', oldInfo[14])
    }

    info = CouponDao().updateCoupon(info)

    if info == -200:
        return jsonify({"message": {"code": 0, "status": "Database Exception: -200"}})
    elif info:
        return jsonify({"info": info, "message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"message": {"code": 0, "status": "Server error!"}})
